// isNewVersion.js
import axios from "axios";
import { ElMessageBox } from "element-plus";

// 检查是否在倒计时中
const isInCountdown = () => {
  const countdownEnd = localStorage.getItem("versionCheckCountdown");
  if (!countdownEnd) return false;
  return new Date().getTime() < parseInt(countdownEnd);
};

// 设置倒计时
const setCountdown = () => {
  const thirtyMinutes = 30 * 60 * 1000; // 30分钟的毫秒数
  const endTime = new Date().getTime() + thirtyMinutes;
  localStorage.setItem("versionCheckCountdown", endTime.toString());
};

// 检查版本
const checkVersion = () => {
  // 如果正在倒计时中，直接返回
  if (isInCountdown()) {
    return;
  }

  const baseUrl = `/version.json?t=${new Date().getTime()}`;
  axios
    .get(baseUrl)
    .then((res) => {
      if (res.status === 200) {
        const webappVersion = res.data.version;
        const localWebappVersion = localStorage.getItem("webappVersion");
        if (localWebappVersion !== webappVersion) {
          // 版本不一致，显示确认对话框
          ElMessageBox.confirm(
            "发现新版本，是否立即刷新页面？",
            "版本更新提示",
            {
              confirmButtonText: "立即刷新",
              cancelButtonText: "30分钟后提醒",
              type: "info",
            }
          )
            .then(() => {
              // 用户确认刷新
              localStorage.setItem("webappVersion", webappVersion);
              window.location.reload();
            })
            .catch(() => {
              // 用户选择稍后提醒
              setCountdown();
            });
        } else {
          // 版本一致，更新本地存储
          localStorage.setItem("webappVersion", webappVersion);
        }
      }
    })
    .catch((error) => {
      console.error("Error checking for new version:", error);
    });
};

// 启动定时检查
export const isNewVersion = (checkIntervalMinutes = 1) => {
  // 立即执行一次检查
  checkVersion();

  // 设置定时检查
  const interval = checkIntervalMinutes * 60 * 1000; // 转换为毫秒
  setInterval(checkVersion, interval);
};
